//
//  UITextView+Emoticon.swift
//  14-表情键盘
//
//  Created by 高伦展 on 2018/2/23.
//  Copyright © 2018年 glz. All rights reserved.
//

import UIKit

/**
 代码复核 - 对重构完成的代码进行检查
 
 1.修改注释
 2.确认是否需要进一步重构
 3.再一次检查返回值和参数
 
 */
extension UITextView{
    
    //图片表情完整字符串内容
    var emoticonText: String {
        
        let attrText = attributedText
        
        var strM = String()
        //遍历属性文本
        attrText?.enumerateAttributes(in: NSRange(location:0,length:attrText!.length), options: [], using: { (dict, range, _) in
            
            //print("\(dict)")
            if let attachment = dict[NSAttributedStringKey.attachment] as? EmoticonAttachment {
                //print(attachment)
                strM += attachment.emoticon.chs ?? ""
            }else{
                let str = (attrText?.string as! NSString).substring(with: range)
                //print(str)
                
                strM += str
            }
            
        })
        
        return strM
    }
    
    func insertEmoticon(em:Emoticon){
        
        if em.isEmpty{
            return
        }
        
        if em.isRemoved{
            deleteBackward()
            return
        }
        
        if let emoji = em.emoji{
            replace(selectedTextRange!, withText: emoji)
        }
        
        insertImageEmoticon(em: em)
        // 通知 ‘代理’文本发生变化
        delegate?.textViewDidChange?(self)
    }
    
    func insertImageEmoticon(em:Emoticon){
        
        let imageText = EmoticonAttachment(emoticon: em).imageText(font: font!)
        
        //记录 textView attributeString -> 转换成可变文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        
        //插入图片文本
        strM.replaceCharacters(in: selectedRange, with: imageText)
        
        //替换属性文本
        //记录光标位置
        let range = selectedRange
        //替换文本
        attributedText = strM
        //恢复光标
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
    
    
}
